package com.kaifamiao.servlet;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.logging.Logger;

public class PassiveServlet implements Servlet {

    private static final String className = PassiveServlet.class.getName();
    private static final Logger logger = Logger.getLogger( className );

    static {
        logger.info( String.format( "初始化[%s]类", className ));
    }

    // 用于保存由容器所传递的ServletConfig对象
    private ServletConfig config;

    public PassiveServlet(){
        super();
        logger.info( String.format("创建[%s]实例",this.toString()) );
    }

    /**
     * Servlet容器 通过 init 方法的 参数 为 servlet 实例传递数据
     * @param config 用来传递数据的对象
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        logger.info( String.format( "初始化[%s]实例" , this.toString() ) );
        this.config = config;
    }

    @Override
    public void service(ServletRequest req, ServletResponse resp)
            throws ServletException, IOException {
        logger.info( String.format( "[%s]正在提供服务", this.toString() ) );
        req.setCharacterEncoding( "UTF-8" );
        resp.setCharacterEncoding( "UTF-8" );
        resp.setContentType( "text/html; charset=UTF-8" );
        PrintWriter out = resp.getWriter();
        out.println( "<p align=\"center\">" + LocalDateTime.now() + "</p>" );
    }

    @Override
    public void destroy() {
        logger.info( String.format( "释放[%s]所占用的资源", this.getClass() ) );
    }

    @Override
    public ServletConfig getServletConfig() {
        return config;
    }

    @Override
    public String getServletInfo() {
        // 返回 servlet-name
        return config.getServletName();
    }

}
